import http from '@/utils/typedHttp';
import type { BusinessSystem, AssessmentType } from '@/types/business';

export interface PaginatedResponse<T> {
  total: number;
  items: T[];
}

export interface AssessmentPlanResponse {
  id: string;
  name: string;
  rating_filing_name: string;
  responsible_person: string;
  business_department: string;
  contact: string;
  assessment_type: AssessmentType;
  template_id:string;
  expected_completion_date: string;
  created_at: string;
  status: 'in_progress' | 'completed';
}

export interface AssessmentPlanCreate {
  name: string;
  rating_filing_name: string;
  responsible_person: string;
  business_department: string;
  contact: string;
  assessment_type: AssessmentType;
  template_id:string;
  expected_completion_date: string;
}

export interface AssessmentPlanUpdate extends Partial<AssessmentPlanCreate> {
  status?: 'in_progress' | 'completed';
}

export interface ListAssessmentPlansParams {
  name?: string;
  status?: 'in_progress' | 'completed';
  assessment_type?: AssessmentType;
  skip?: number;
  limit?: number;
}

const ASSESSMENT_PLANS_API = '/assessment-plans';

export const businessApi = {
  // List assessment plans with pagination and filtering
  async list(params?: ListAssessmentPlansParams): Promise<PaginatedResponse<AssessmentPlanResponse>> {
    try {
      const { items = [], total = 0 } = await http.get<PaginatedResponse<AssessmentPlanResponse>>(
        `${ASSESSMENT_PLANS_API}/`, 
        { 
          params: {
            skip: 0,
            limit: 100,
            ...params,
          } 
        }
      );
      
      return {
        total,
        items: Array.isArray(items) ? items : [],
      };
    } catch (error) {
      console.error('Error in businessApi.list:', error);
      // Return empty result instead of throwing to prevent UI crashes
      return {
        total: 0,
        items: [],
      };
    }
  },

  // Get a single assessment plan by ID
  async getById(id: string): Promise<AssessmentPlanResponse> {
    return http.get<AssessmentPlanResponse>(`${ASSESSMENT_PLANS_API}/${id}`);
  },

  // Create a new assessment plan
  async create(plan: AssessmentPlanCreate): Promise<AssessmentPlanResponse> {
    return http.post<AssessmentPlanResponse>(`${ASSESSMENT_PLANS_API}/`, plan);
  },

  // Update an existing assessment plan
  async update(id: string, updates: AssessmentPlanUpdate): Promise<AssessmentPlanResponse> {
    return http.put<AssessmentPlanResponse>(`${ASSESSMENT_PLANS_API}/${id}`, updates);
  },

  // Delete an assessment plan
  async delete(id: string): Promise<void> {
    await http.delete<void>(`${ASSESSMENT_PLANS_API}/${id}`);
  },

  // Get business statistics by calculating from the list of assessment plans
  async getStatistics(): Promise<{ total: number; inProgress: number; completed: number }> {
    try {
      const { items, total } = await this.list();
      const inProgress = items.filter(item => item.status === 'in_progress').length;
      const completed = items.filter(item => item.status === 'completed').length;
      
      return {
        total: total || items.length,
        inProgress,
        completed,
      };
    } catch (error) {
      console.error('Error calculating statistics:', error);
      return {
        total: 0,
        inProgress: 0,
        completed: 0,
      };
    }
  },

  // Convert API response to BusinessSystem type
  toBusinessSystem(plan: AssessmentPlanResponse): BusinessSystem {
    return {
      id: plan.id,
      name: plan.name,
      ratingFilingName: plan.rating_filing_name,
      responsiblePerson: plan.responsible_person,
      businessDepartment: plan.business_department,
      contact: plan.contact,
      templateID: plan.template_id,
      assessmentType: plan.assessment_type,
      expectedCompletionDate: plan.expected_completion_date.split('T')[0],
      createdAt: plan.created_at.split('T')[0],
      status: plan.status,
    };
  },

  // Convert BusinessSystem to API create/update format
  fromBusinessSystem(system: Partial<BusinessSystem>): Partial<AssessmentPlanCreate> {
    return {
      name: system.name,
      rating_filing_name: system.ratingFilingName,
      responsible_person: system.responsiblePerson,
      business_department: system.businessDepartment,
      contact: system.contact,
      assessment_type: system.assessmentType,
      template_id: system.templateID,
      expected_completion_date: system.expectedCompletionDate ? 
        `${system.expectedCompletionDate}T00:00:00Z` : undefined,
    };
  }
};

export default businessApi;
